"use client";

import { Breadcrumb } from "@/components/ui/breadcrumb";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { FileItemComponent } from "@/components/ui/file-item";
import { Input } from "@/components/ui/input";
import { MoveDialog } from "@/components/ui/move-dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { UploadArea } from "@/components/ui/upload-area";
import { PasswordDialog } from "@/components/ui/password-dialog";
import { FileItem, useCreateDirectory, useDeleteFile, useFiles, useMoveFile } from "@/hooks/useFiles";
import { Folder, FolderPlus, Search } from "lucide-react";
import { useState, useEffect } from "react";
import { toast } from "sonner";

export default function ManagementPage() {
    const [isAuthenticated, setIsAuthenticated] = useState(false);
    const [showPasswordDialog, setShowPasswordDialog] = useState(true);

    const [currentPath, setCurrentPath] = useState("");
    const [searchTerm, setSearchTerm] = useState("");
    const [sortBy, setSortBy] = useState<"name" | "type" | "size" | "modifiedTime">("name");
    const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");
    const [newFolderName, setNewFolderName] = useState("");
    const [open, setOpen] = useState(false);
    const [moveDialogOpen, setMoveDialogOpen] = useState(false);
    const [selectedItem, setSelectedItem] = useState<FileItem | null>(null);

    // 检查本地存储的认证状态
    useEffect(() => {
        const authStatus = sessionStorage.getItem("management_authenticated");
        if (authStatus === "true") {
            setIsAuthenticated(true);
            setShowPasswordDialog(false);
        }
    }, []);

    const handlePasswordSuccess = () => {
        setIsAuthenticated(true);
        setShowPasswordDialog(false);
        sessionStorage.setItem("management_authenticated", "true");
    };

    const {
        data: filesData,
        isLoading,
        error,
    } = useFiles({
        path: currentPath,
        search: searchTerm,
        sortBy,
        sortOrder,
    });

    const deleteMutation = useDeleteFile();
    const createDirectoryMutation = useCreateDirectory();
    const moveMutation = useMoveFile();

    const handleNavigate = (path: string) => {
        setCurrentPath(path);
    };

    const handleDelete = (path: string, type: "file" | "directory") => {
        if (confirm(`确定要删除这个${type === "directory" ? "文件夹" : "文件"}吗？`)) {
            deleteMutation.mutate(
                { path, type },
                {
                    onSuccess: () => {
                        toast.success("删除成功");
                    },
                    onError: (error) => {
                        toast.error(`删除失败: ${error.message}`);
                    },
                }
            );
        }
    };

    const handleCopyLink = (path: string) => {
        const url = `${window.location.origin}/view?model=${encodeURIComponent(path)}`;
        navigator.clipboard.writeText(url).then(() => {
            toast.success("链接已复制到剪贴板");
        });
    };

    const handleMove = (sourcePath: string, targetPath: string, type: "file" | "directory") => {
        // 找到要移动的项目
        const item = filesData?.data?.find((item: FileItem) => item.path === sourcePath);
        if (item) {
            setSelectedItem(item);
            setMoveDialogOpen(true);
        }
    };

    const handleConfirmMove = (sourcePath: string, targetPath: string, type: "file" | "directory") => {
        moveMutation.mutate(
            { sourcePath, targetPath, type },
            {
                onSuccess: () => {
                    toast.success("移动成功");
                    setMoveDialogOpen(false);
                    setSelectedItem(null);
                },
                onError: (error) => {
                    toast.error(`移动失败: ${error.message}`);
                },
            }
        );
    };

    const handleCreateFolder = () => {
        if (!newFolderName.trim()) {
            toast.error("请输入文件夹名称");
            return;
        }

        createDirectoryMutation.mutate(
            { path: currentPath, name: newFolderName.trim() },
            {
                onSuccess: () => {
                    toast.success("文件夹创建成功");
                    setNewFolderName("");
                    setOpen(false);
                },
                onError: (error) => {
                    toast.error(`创建失败: ${error.message}`);
                },
            }
        );
    };

    // 如果未认证，显示密码验证弹窗
    if (!isAuthenticated) {
        return <PasswordDialog open={showPasswordDialog} onSuccess={handlePasswordSuccess} />;
    }

    if (error) {
        return (
            <div className="flex items-center justify-center h-96">
                <p className="text-destructive">加载失败: {error.message}</p>
            </div>
        );
    }

    return (
        <div className="flex h-screen bg-background">
            {/* 左侧上传区域 */}
            <div className="w-80 border-r border-border p-6 space-y-6">
                <div>
                    <h2 className="text-lg font-semibold mb-4">上传模型</h2>
                    <UploadArea currentPath={currentPath} />
                </div>
            </div>

            {/* 右侧文件列表 */}
            <div className="flex-1 flex flex-col">
                {/* 顶部工具栏 */}
                <div className="border-b border-border p-4 space-y-4">
                    <div className="flex items-center justify-between">
                        <Breadcrumb path={currentPath} onNavigate={handleNavigate} />
                        <div>
                            <Dialog open={open} onOpenChange={setOpen}>
                                <DialogTrigger asChild>
                                    <Button variant="default" className="w-full">
                                        <FolderPlus className="mr-2 h-4 w-4" />
                                        新建文件夹
                                    </Button>
                                </DialogTrigger>
                                <DialogContent>
                                    <DialogHeader>
                                        <DialogTitle>创建新文件夹</DialogTitle>
                                    </DialogHeader>
                                    <div className="space-y-4">
                                        <Input
                                            placeholder="输入文件夹名称"
                                            value={newFolderName}
                                            onChange={(e) => setNewFolderName(e.target.value)}
                                            onKeyDown={(e) => {
                                                if (e.key === "Enter") {
                                                    handleCreateFolder();
                                                }
                                            }}
                                        />
                                        <Button onClick={handleCreateFolder} className="w-full">
                                            创建
                                        </Button>
                                    </div>
                                </DialogContent>
                            </Dialog>
                        </div>
                    </div>

                    <div className="flex items-center space-x-4">
                        <div className="flex-1 relative">
                            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                            <Input placeholder="搜索文件..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="pl-10" />
                        </div>

                        {/* <select value={sortBy} onChange={(e) => setSortBy(e.target.value as any)} className="px-3 py-2 border border-input rounded-md bg-background">
                            <option value="name">按名称</option>
                            <option value="type">按类型</option>
                            <option value="size">按大小</option>
                            <option value="modifiedTime">按修改时间</option>
                        </select> */}

                        <Select value={sortBy} onValueChange={(value) => setSortBy(value as "name" | "type" | "size" | "modifiedTime")}>
                            <SelectTrigger>
                                <SelectValue placeholder="选择排序方式" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="name">按名称</SelectItem>
                                <SelectItem value="type">按类型</SelectItem>
                                <SelectItem value="size">按大小</SelectItem>
                                <SelectItem value="modifiedTime">按修改时间</SelectItem>
                            </SelectContent>
                        </Select>

                        <Button variant="outline" size="sm" onClick={() => setSortOrder(sortOrder === "asc" ? "desc" : "asc")}>
                            {sortOrder === "asc" ? "↑" : "↓"}
                        </Button>
                    </div>
                </div>

                {/* 文件列表 */}
                <div className="flex-1 overflow-auto p-4">
                    {isLoading ? (
                        <div className="flex items-center justify-center h-64">
                            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                        </div>
                    ) : filesData?.data?.length === 0 ? (
                        <div className="flex flex-col items-center justify-center h-64 text-muted-foreground">
                            <Folder className="h-12 w-12 mb-4" />
                            <p>当前目录为空</p>
                        </div>
                    ) : (
                        <div className="space-y-2">
                            {filesData?.data?.map((item: FileItem) => (
                                <FileItemComponent key={item.path} item={item} onNavigate={handleNavigate} onDelete={handleDelete} onCopyLink={handleCopyLink} onMove={handleMove} />
                            ))}
                        </div>
                    )}
                </div>
            </div>

            {/* 移动对话框 */}
            <MoveDialog open={moveDialogOpen} onOpenChange={setMoveDialogOpen} sourceItem={selectedItem} onMove={handleConfirmMove} />
        </div>
    );
}
